package com.xuan.yuapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.xuan.yuapiclientsdk.model.User;


import java.util.HashMap;
import java.util.Map;

import static com.xuan.yuapiclientsdk.utils.SignUtils.getSign;


public class YuApiClient {

    private final String accessKey;
    private final String secretKey;

    public YuApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result1 = HttpUtil.get("http://localhost:8088/user/", paramMap);
        System.out.println("result1: " + result1);
        return result1;
    }

    public String getNameByPost(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        Map<String, Object> paramMap2 = new HashMap<>();
        paramMap2.put("name", name);
        String result2 = HttpUtil.post("http://localhost:8088/user/", paramMap2);
        System.out.println("result2: " + result2);
        return result2;
    }


    public String getNameByJson(User user) {
        String jsonStr = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post("http://localhost:8088/user/json")
                .addHeaders(getHeaderMap(jsonStr))
                .body(jsonStr)
                .execute();
        int status = httpResponse.getStatus();
        String result3 = httpResponse.body();
        System.out.println("status: " + status);
        System.out.println("result3: " + result3);
        return result3;
    }

    private Map<String, String> getHeaderMap(String jsonStr) {
        // 用户参数
        // 时间戳
        // 随机数
        // accessKey
        // sign
        Map<String, String> map = new HashMap<>();
        map.put("body", jsonStr);
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("nonce", RandomUtil.randomNumbers(4));
        map.put("accessKey", accessKey);
        map.put("sign", getSign(jsonStr, secretKey));
        return map;
    }




}
